import sys
import requests
import json


class RequestBasedHueObject(object):
    # I want to allow users to set more than one attribute at once, so
    # I need to allow the transmission of an additional data dictionary
    # with each __setattr__() call, e.g.:
    # lamp1.hue = 20000, {'bri': 200}
    # would allow someone to set lamp1.hue=20000 and lamp1.bri=200 with
    # one underlying request.  There may be a more elegant way to implement
    # this, I don't know.

    READ_ONLY_ATTRIBUTES = []

    def __setattr__(self, attr, tuple_):
        if not isinstance(tuple_, tuple):
            tuple_ = (tuple_,)

        val = tuple_[0]

        try:
            data = tuple_[1]
        except IndexError:
            data = {}

        data.update( {attr: val} )

        result = requests.put( self.PUT_URL, data=json.dumps(data),
                                    timeout=self.TIMEOUT )

        print data, result, result.json

        if result.status_code == 200:
            for key, val in data.iteritems():
                self.setattr_(key, val, virtual=True)
        else:
            sys.stderr.write( "Failed to set attribute %s = %s for %s.\n" %
                                               (attr, str(val), str(self)) )

    def setattr_(self, attr, val, virtual=False):
        if virtual:
            object.__setattr__(self, attr, val)
        else:
            if attr in self.__class__.READ_ONLY_ATTRIBUTES:
                sys.stderr.write("%s is a read-only attribute!\n" % key)
                return

            self.__setattr__(attr, val)
